from flask import Flask
from flask_login import LoginManager
from .database import db, load_db_data
from datetime import datetime

# 加载保存的数据
load_db_data()

login_manager = LoginManager()

def create_app(config=None):
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'dev-secret-key-123'  # 直接设置密钥
    
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'  # 登录视图
    
    # 注册蓝图
    from .routes import main_bp, auth_bp, api_bp
    app.register_blueprint(main_bp)
    app.register_blueprint(auth_bp)
    app.register_blueprint(api_bp, url_prefix='/api')
    
    @login_manager.user_loader
    def load_user(user_id):
        from .models.user import User
        return User.find_by_id(user_id)
    
    # 添加自定义过滤器
    @app.template_filter('datetime')
    def format_datetime(value):
        if not value:
            return ''
        if isinstance(value, str):
            try:
                value = datetime.fromisoformat(value.replace('Z', '+00:00'))
            except:
                return value
        return value.strftime('%Y-%m-%d %H:%M')
    
    return app 